package com.douyin.controller;

import com.douyin.entity.ApiLog;
import com.douyin.service.LogService;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/monitor")
public class MonitorController {

    private final LogService logService;
    private final MeterRegistry meterRegistry;

    @Autowired
    public MonitorController(LogService logService, MeterRegistry meterRegistry) {
        this.logService = logService;
        this.meterRegistry = meterRegistry;
    }

    @GetMapping("/logs")
    public List<ApiLog> getRecentLogs() {
        return logService.getAllRecentLogs(500);
    }

    @GetMapping("/metrics")
    public Map<String, Object> getMetrics() {
        List<ApiLog> apiLogs = logService.getAllRecentLogs(500);
        Map<String, Object> metrics = new HashMap<>();

        // 1. 计算总请求次数
        long totalRequests = apiLogs.size();
        metrics.put("totalRequests", totalRequests);

        // 2. 计算平均耗时（单位：毫秒，转换为秒）
        double avgDurationMs = apiLogs.stream()
                .mapToLong(ApiLog::getDuration)
                .average()
                .orElse(0);
        metrics.put("avgDuration", avgDurationMs / 1000); // 转换为秒

        // 3. 计算状态码分布
        Map<String, Long> statusDistribution = new HashMap<>();
        statusDistribution.put("2xx", apiLogs.stream()
                .filter(log -> log.getStatus() >= 200 && log.getStatus() < 300)
                .count());
        statusDistribution.put("4xx", apiLogs.stream()
                .filter(log -> log.getStatus() >= 400 && log.getStatus() < 500)
                .count());
        statusDistribution.put("5xx", apiLogs.stream()
                .filter(log -> log.getStatus() >= 500 && log.getStatus() < 600)
                .count());
        metrics.put("statusDistribution", statusDistribution);

        return metrics;
    }
}